package com.soulmate.gateway.manager;

import lombok.AllArgsConstructor;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.token.Token;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/**
 * @author huaiping
 */
@Component
@AllArgsConstructor
public class GatewayAuthenticationManger implements ReactiveAuthenticationManager {
    private TokenService tokenService;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        return Mono.justOrEmpty(authentication)
                .filter(filter -> filter instanceof Token)
                .cast(Token.class)
                .map(Token::getExtendedInformation)
                .flatMap(accessToken -> {
                    Token verifiedToken = tokenService.verifyToken(accessToken);
                    if (Objects.isNull(verifiedToken)) {
                        return Mono.empty();
                    } else if (verifiedToken.getKeyCreationTime() > 0) {
                        return Mono.empty();
                    }
                    // String extendedInformation = verifiedToken.getExtendedInformation();
                    return Mono.just(new UsernamePasswordAuthenticationToken("zhangsan",
                            "123456", List.of(new SimpleGrantedAuthority("ADMIN"))));
                });
    }
}
